<template>
  <div class="chart-content-wrapper" @mouseenter="mouseenter()" @mouseleave="mouseleave">
    <top-filter :title="reportName" ref="topFilter">
      <double-check-filter :isParentLinkChild="true" @confirmDoubleSelect="planAreaSelect" defaultText="统筹区" :filter="filterN" type="planArea"></double-check-filter>
      <single-list-filter-without-cb :defaultText="'医疗类别'" :filter="filterN" :type="'insuredType'" @confirmSingleSelect="confirmSingleSelect"></single-list-filter-without-cb>
      <double-check-filter :isParentLinkChild="true" @confirmDoubleSelect="confirmDoubleSelect" defaultText="费用类型" :filter="filterN" type="freeType"></double-check-filter>
    </top-filter>
    <div class="chart-container" v-show="isShowChart">
      <div id="myChart1" class="chart-type1"  >
        <i class="el-icon-edit"></i>
      </div>
      <Summarize :showSummarizeText="conclusion"></Summarize>
    </div>
 </div>
</template>

<script>
  import {setChartHeight,loadingOpt,isJanuary} from '../../../assets/js/utils.js'
  import {getChartItem1} from '../../../api/api'
  import SingleListFilter from '../../last/filter/single-list-filter.vue'
  import DoubleCheckFilter from '../../last/filter/double-check-filter.vue'
  import TopFilter from '../../last/filter/top-filter1.vue'
  import Summarize from '../../last/summarize/summarize.vue'
  import SingleListFilterWithoutCb from '../../last/filter/single-list-filter-without-checkbox'
export default {
  name: 'chart1',
  props: ['isChange','filter'],
  components: {
    SingleListFilter,
    DoubleCheckFilter,
    TopFilter,
    Summarize,
    SingleListFilterWithoutCb
  },
  data () {
    return {
      filterN: JSON.parse(JSON.stringify(this.filter)),
      conclusion:'',
      areaCode: null,
      costType: null,
      medicalCategory: null,
      reportName:'2013年-2018年区域医疗费用增长趋势分析',
      isTotal:true,
      isShowChart:true,
      height:400,
      option:{}
    }
  },
  mounted(){
    let areaCode = []
    this.filter.nc.planArea.map((item,index)=>{
      if(index>0&&index<=6){
        areaCode.push(item.selectId)
      }
    })
    this.areaCode = areaCode.join(',');
    setChartHeight();
    this.myChart = this.$echarts.init(document.getElementById('myChart1') ,null, {renderer: 'canvas'})
    //首次渲染
    this.getData();
    let that = this;
    this.myChart.on('legendselectchanged',function(params){
      let option = this.getOption();
      let select_key = Object.keys(params.selected);
      if (!params.selected[params.name]) {
        select_key.map(res => {
          option.legend[0].selected[res] = true;
        });
      } else {
        select_key.map(res => {
          option.legend[0].selected[res] = true;
        });
        option.legend[0].selected[params.name] = true;
      }
      let legend = []
      that.myChart.dispatchAction({
        type: 'legendselectchanged',
        batch: legend
      });
      that.myChart.setOption(option)
    })
    this.myChart.on('click', function (params) {
      let hash = window.location.hash;
      let data = {
        hash,
      }
      if(that.medicalCategory==''){
        that.medicalCategory = null;
      }
      if(that.areaCode==''){
        that.areaCode = null;
      }
      if(params.componentSubType==='bar'){
        that.$router.push({path:`/report/chartDetail1/${params.name}/${that.areaCode}/${that.costType}/${that.medicalCategory}/detail`,query:data})
      }
    });
  },
  activated(){
    this.getData();
  },
  watch:{
    isChange(){
      setTimeout(()=>{
        setChartHeight();
        setTimeout(()=>{
          this.myChart.resize();
        },10)
      },101)
    }
  },
  methods:{
    mouseenter(){
      this.$refs.topFilter._hideChartTitle()
    },
    mouseleave() {
      this.$refs.topFilter._showChartTitle()
    },
    getData(){
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        this.myChart.clear();
        this.myChart.showLoading(loadingOpt)
        getChartItem1('report/medExpGrowthTrendAnalysis',this.areaCode, this.costType,  this.medicalCategory).then(response=>{
          let json = response.data;
          if(response.code===0){
            this.isShowChart = true;
            this.myChart.hideLoading();
            this.reportName = json.reportName;
            this.conclusion = json.reportConclusion;
            this.drawLine(json)
          }else{
            this.isShowChart = false;
          }
        }).catch(res=>{
          this.isShowChart = false;
        })
      },300)
    },
    confirmSingleSelect(filter) {
      //医疗类别选择
      this.medicalCategory = filter;
      this.getData();
    },
    confirmDoubleSelect(filter){
      //费用类型选择
      this.costType = filter.join(',');
      this.getData();
    },
    planAreaSelect(filter){
      //统筹区选择
      this.areaCode = filter.join(',')
      this.getData();
    },
    drawLine(json){
      // 格式化负增长数据，为0时设为空
      json.negativeIncreaseQuotaList.map((item,index)=>{
        if(item==0){
          json.negativeIncreaseQuotaList[index]=''
        }
      })
      let boundaryNum = isJanuary();
      // 基于准备好的dom，初始化echarts实例
      // 绘制图表
      this.myChart.setOption({
        title:{
          subtext: '单位 : 万元',
          left:'80%',
          top:95,
          x:'left',
          subtextStyle:{
            color:'#fff'
          }
        },
        // Make gradient line here
        grid:[//此参数可在一个dom中划分多个图表 可设置不同图表的位置
          {
            height:60,
            top:35,
            left:60,
            right:50,
            tooltip: {
              formatter: "{b}</br>{c}%" //给当前坐标系添加弹窗
            }
          },
          {
            top:130,
            bottom:40,
            right:35,
            left:65,
            tooltip: {
              show:false,
            }
          }
        ],
        legend: {
          top:'95%',
          left:'center',
          icon:'rect',
          itemWidth: 30,
          itemHeight: 6,
          itemGap: 20,
          tooltip: {
            show: true,
            formatter:function(params){
              let txt = '';
              if(params.name=='增长额(正)'){
                txt = '即区域内医疗机构医疗总收入增长额=（区</br>域内医疗机构本年度住院收入+本年度门</br>诊收入）-（区域内医疗机构上年度住院收</br>入+上年度门诊收入）'
              }else if(params.name=='增长额(负)'){
                txt = '即区域内医疗机构医疗总收入增长额=（区</br>域内医疗机构本年度住院收入+本年度门</br>诊收入）-（区域内医疗机构上年度住院收</br>入+上年度门诊收入）'
              }else{
                txt = '医疗总费用'
              }
              return txt;
            }
          },
          data:['医疗总费用','增长额(正)',{
            name:'增长额(负)',
          },
          ],
          textStyle:{
            color:'#fff'
          },
         // selectedMode: false
        },
        tooltip: {
          show:true,
          textStyle :{
            fontSize:12
          },
          // trigger: 'axis',
          // axisPointer : {
          //   type : 'shadow'
          // }
        },
        xAxis: [{
          data: json.yearList,
          show:true,
          axisLine:{
            show:true,//显示x轴坐标线并设置为虚线
            lineStyle:{
              color:'#294363'
            }
          },
          axisTick:{
            show:false //不显示x轴坐标的刻度
          },
          axisLabel:{
            show:false //不显示x轴坐标数值
          }
        }, {
          data: json.yearList,
          gridIndex: 1,
          axisLine:{ //x轴的横线是否显示
            show:true,
            lineStyle:{
              color:'#2a4565'
            }
          },
          axisTick:{ //x轴的刻度短竖线是否显示
            show:false
          },
          axisLabel : {
            formatter: '{value}',
            textStyle: {
              color: '#fff'
            }
          },
        }],
        yAxis: [{
          splitLine: {
            show: false
          },
          position:'right',
          /*minInterval:40,*/
          /*max:'dataMax',*/
         /* min:'dataMin',*/
          splitNumber:2,
          axisLine:{
            show:false,
          },
          axisTick:{
            show:false
          },
          axisLabel : {
            formatter: '{value}',
            textStyle: {
              color: '#fff'
            }
          },
        }, {
          splitLine: {
            show: true,
            lineStyle:{
              color:'#2a4565',
              type:'dashed'
            }
          },
          gridIndex: 1,
          axisLine:{
            show:true,
            lineStyle:{
              color:'#2a4565'
            }
          },
          axisTick:{
            show:false
          },
          axisLabel : {
            formatter: '{value}',
            textStyle: {
              color: '#fff'
            }
          },
        }],
        visualMap: [{
          show: true,
          dimension: 0,
          seriesIndex: 0,
          left: 'center',
          top: 'top',
          itemWidth:10,
          itemHeight:10,
          orient:"horizontal",
          textStyle:{
            color:'#fff'
          },
          pieces:[
            {
              lte: boundaryNum.preStart,
              color: '#129cff',
              symbol:'circle',
              name:'增长率（环比）',
              label: '增长率（环比）',
            }, {
              gt: boundaryNum.preStart,
              lte: boundaryNum.nextEnd,
              symbol:'circle',
              color: '#67ffdb',
              label: '增长率（同比）',
              name:'增长率（同比）',
            }
          ],
        }],
        series: [{
          type: 'line',
          showSymbol: true,
          name:'增长率(环比/同比)',
          data: json.yearlyGrowthRateList,
          symbolSize: 10,
          tooltip:{
            show:true,
            formatter:function(params){
             return `<span style="color:${params.color}">${params.name}</span></br><span style='color:#c7c7c7'>${params.value}%</span>`
            }
          },
          label:{
            show:true,
            position:'top',
            formatter:'{c}%',
            color:'#fff'
          },
            markLine:{
            label:{
              position: 'start',
              formatter: '{c}%',
              color:'#fff'
            },
              symbol: 'none',//设置平均线的没样式
            data : [
              {
                type : 'average',
                name: '平均增长率',
                tooltip:{
                  show:true,
                  formatter(params){
                    return `<span style="color:${params.color}">平均增长率</span></br><span style='color:#c7c7c7'>${params.value}%</span>`
                  }
                }
              }
            ],
            lineStyle: {
              color:'#ff6a93'
            }
          }
        }, {
          type: 'bar',
          name: '医疗总费用',
          stack:'总额',
          data: json.yearlyTotalCostList,
          color:'#ff6a93',
          barWidth: '40%',
          xAxisIndex: 1,
          yAxisIndex: 1,
          z:2,
        },{
          type: 'bar',
          name:'增长额(正)',//此值与legend图例对应
          stack:'总额',
          color:'#ffd66a',
          data: json.positiveIncreaseQuotaList,
          label:{
            show:true,
            color:'#fff',
            position:'top',
            formatter:function(params){
              let val = ''
              let arr = json.yearlyTotalCostList;
              arr.map((item,index)=>{
                if(params.dataIndex==index){
                  if(Math.round((arr[index]+params.value)*100)%10==0){
                    val = (arr[index]+params.value).toFixed(1)
                  }else if(Math.round((arr[index]+params.value)*100)%100==0){
                    val = (arr[index]+params.value).toFixed(0)
                  }else{
                    val = (arr[index]+params.value).toFixed(2)
                  }
                }
              })
              return val;
            }
          },
          tooltip:{
            show:true,
            formatter:function(params){
              return `<span style="color:${params.color}">${params.name}</span></br><span style='color:#c7c7c7'>${params.value}万元</span>`
            }
          },
          barWidth: '40%',
          xAxisIndex: 1,
          yAxisIndex: 1,
        },{
          type: 'bar',
          name:'增长额(负)',
          showSymbol: false,
          z:1,
          tooltip:{
            show:true,
            formatter:function(params){
              return `<span style="color:#67ffdb">${params.name}</span></br><span style='color:#c7c7c7'>${params.value}万元</span>`
            }
          },
          stack:'总额',
          itemStyle:{
            /*borderType:'dashed',
            borderColor:'#67ffdb',*/
            color:'#263b5e',
          },
          data: json.negativeIncreaseQuotaList,
          barWidth: '40%',
          xAxisIndex: 1,
          yAxisIndex: 1
        }]
      });
      this.option = JSON.stringify(this.myChart.getOption());
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>
